class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class ListServices:
    def __init__(self, head=None):
        self.head = head 

    # 辅助函数，创建链表
    @staticmethod 
    def create_linked_list(arr):
        if not arr:
            return None 
        head = ListNode(arr[0])
        current = head 
        for val in arr[1:]:
            current.next = ListNode(val)
            current = current.next 
        return head 
    
    # 辅助函数，打印链表
    @staticmethod 
    def print_linked_list(head):
        result = []
        while head:
            result.append(str(head.val))
            head = head.next 
        print("->".join(result))

    # 合并链表 hard
    @staticmethod
    def merge(list1, list2):
        # 其实我这里还没有定义什么时候是 None
        # 知道意思就行！
        if not list1 and not list2:
            print("不能传入两个空链表")
        # 新建链表哑节点
        dummy = ListNode(None)

        # while 循环控制对两个链表值的比较
        # 什么时候哪个链表为空了，就取消循环
        # 如果表一的值小于表二的值，新的链表就承接表一的值，否则承接表二的值
        # 如果表一的值等于表二的值，那么就连接其中一个的，然后都跳到下一个去比较

        # 判断哪个链表为空了
        # 哪个链表不为空就接着下去就好了


    # 反转部分链表
    def reverse_between(self, m: int, n: int):
        """
        反转特定区间内的链表
        """
        dummy = ListNode(0)
        dummy.next = self.head 
        prev = dummy
        
        for i in range(m-1):
            prev = prev.next 

        curr = prev.next 

        for i in range(n-m):
            next = curr.next 
            curr.next = next.next 
            prev.next = next 
            next.next = curr 
            
        self.head = dummy.next 
        return self.head

    # 检测移除环链表
    def detectAndRemoveLoop(self):
        """
        检测并删除链表中的环
        """
        if not self.head or self.head.next is None:
            # not self.head or not self.head.next
            return False

        slow = self.head.next
        fast = self.head.next.next
        loopExists = False

        while fast != slow:
            if fast is None or fast.next is None:
                return False
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                loopExists = True
                break

        if not loopExists:
            return False

        # 找到环的入口
        slow = self.head
        while slow != fast:
            slow = slow.next
            fast = fast.next
        # 这个时候只能一步一步走，它们只有可能在入口的地方相遇

        # 摧毁掉这个链表环
        fast.next = None



    

